package com.lilingguo.easyserver.job;

import com.lilingguo.easyserver.config.ServerProperties;
import com.lilingguo.easyserver.container.Container;
import com.lilingguo.easyserver.pojo.Monitor;
import com.lilingguo.easyserver.pojo.Persistence;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 定时任务
 * 清理过期服务
 *
 * @Author: 黎铃果
 * @Date: 2020/05/28 16:39
 */
@Log4j2
@Component
public class ClearExpiredInfoJob implements Runnable {

    @Autowired
    private Container container;
    @Autowired
    private Monitor monitor;
    @Autowired
    private Persistence persistence;
    @Autowired
    private ServerProperties serverProperties;

    /**
     * 记录当前定时任务的执行次数
     */
    private static int count = 0;
    /**
     * 数据持久化周期
     */
    private static int cycle = 3;

    @Override
    public void run() {
        this.doPersistence();
        log.info("ready to clear serviceInfos");
        // self protection
        if (serverProperties.isSelfProtection()) {
            int size = container.getAllData().size();
            int tickCount = monitor.getTickCount();
            monitor.setTickCount(0);
            // 计算期望值 (tick/min)
            int expectedValue = (int) (size * 2 * 0.75);
            // 计算实际值 (tick/min)
            int actualValue = (int) (60000.0 / serverProperties.getClearRate() * tickCount);
            boolean after = actualValue < expectedValue;
            boolean before = monitor.isSelfProtection();
            if (after != before) {
                monitor.setSelfProtection(after);
                if (after) {
                    log.warn("start self protecting");
                } else {
                    log.warn("stop self protecting");
                }
            }
        }

        if (!monitor.isSelfProtection()) {
            container.removeExpiredInfos();
        }
    }

    private void doPersistence() {
        if (persistence != null && persistence.isLoaded()) {
            count++;
            if (count % cycle == 0) {
                persistence.save(container.getAllData());
            }
        }
    }
}
